package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.AddressService;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartService cartService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override   //生成订单
    public void save(Order order) {
        //order传入信息 addressId地址id  payMethod支付方式  remark备注
        //1.获取登录顾客信息
        User user = UserHolder.get();

        //2.获取购物车信息
        List<Cart> cartList = cartService.findCart();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("当前购物车为空,无法生成订单");
        }
        //3.获取顾客地址信息
        Address address = addressService.findById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址不存在,无法生成订单");
        }

        //4.生成订单表id
        order.setId(IdWorker.getId());//(mybatisPlus工具类雪花算法生成)

        //5.total: 统计总金额
        BigDecimal total = new BigDecimal(0);

        //6.遍历购物车  生成订单明细表
        for (Cart cart : cartList) {
            //7.创建订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            //设置属性
            orderDetail.setName(cart.getName());//名称
            orderDetail.setOrderId(order.getId());//订单id
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());//口味
            orderDetail.setNumber(cart.getNumber());//数量
            orderDetail.setAmount(cart.getAmount());//金额
            orderDetail.setImage(cart.getImage());//图片

            //将该条明细插入明细表中
            orderDetailMapper.insert(orderDetail);

            //总金额 total = total + amount * number
            total = total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        //8.生成订单表
        order.setNumber(order.getId() + ""); //订单号
        order.setStatus(1);//订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        order.setUserId(user.getId());//下单用户id
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());//TODO 结账的时候再更新时间
        order.setAmount(total);//实收金额
        order.setUserName(user.getName());//用户名
        order.setPhone(address.getPhone());//手机号
        order.setAddress(address.getDetail());//地址
        order.setConsignee(address.getConsignee());//收货人
        //将订单插入订单表中
        orderMapper.insert(order);

        //9.清空购物车
        cartService.cartClean();
    }

    @Override   //分页查询订单 app端
    public Page<Order> findUserPage(Integer pageNum, Integer pageSize) {
        //1.分页查询订单
        Page<Order> page = new Page<>(pageNum, pageSize);
        //条件: 当前登录顾客  排序: 根据时间排序 新的订单在前
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getUserId, UserHolder.get().getId());
        //根据下单时间排序
        orderLambdaQueryWrapper.orderByDesc(Order::getOrderTime);
        //查询order订单
        page = orderMapper.selectPage(page, orderLambdaQueryWrapper);
        //根据order订单id查询订单明细表
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {

                LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, order.getId());
                //查询订单明细表
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
                //将订单明细放入order中
                order.setOrderDetails(orderDetailList);

                Integer total = 0;
                if (CollectionUtil.isNotEmpty(orderDetailList)) {
                    for (OrderDetail orderDetail : orderDetailList) {
                        total += orderDetail.getNumber();
                    }
                }
                order.setSumNum(total);//商品数量:订单明细数量总和
            }
        }
        return page;
    }

    @Override   //分页查询订单
    public Page<Order> findByPage(Integer pageNum, Integer pageSize, String number, String beginTime, String endTime) {

        //1.分页查询订单
        Page<Order> page = new Page<>(pageNum, pageSize);
        //条件: 当前登录顾客  排序: 根据时间排序 新的订单在前
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.like(number != null, Order::getNumber, number);
        if (beginTime != null && endTime != null)
            orderLambdaQueryWrapper.between(Order::getOrderTime, beginTime, endTime);
        //根据下单时间排序
        orderLambdaQueryWrapper.orderByDesc(Order::getOrderTime);
        //查询order订单
        page = orderMapper.selectPage(page, orderLambdaQueryWrapper);

        //遍历订单,查询订单明细
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
                order.setOrderDetails(orderDetailList);
            }
        }
        return page;


    }

}
